<template>
  <div class="homeCode">
    <!-- SQL编辑器 -->
    <codemirror-editor
      ref="codemirrorEditor"
      :run-loading="runLoading"
      @input="onEditorInput"
      @run="onSQLRun"
    ></codemirror-editor>
    <div class="tables-result" :style="{ height: `calc(100vh - 340px)` }">
      <el-tabs
        type="border-card"
        v-model="activeName"
        @tab-click="changeTab"
        style="height: 99%"
      >
        <el-tab-pane label="信息" name="info">
          <span
            v-if="runType === 0"
            class="el-icon-info"
            style="color: #909399"
          ></span>
          <span
            v-if="runType === 1"
            class="el-icon-success"
            style="color: #67c23a"
          ></span>
          <span
            v-if="runType === 2"
            class="el-icon-warning"
            style="color: #e6a23c"
          ></span>
          <span
            v-if="runType === 3"
            class="el-icon-error"
            style="color: #f56c6c"
          ></span>
          {{ runResult }}
          <template v-if="runType === 3">
            <div class="error-message">
              <b>message：</b>{{ errMsg.sqlMessage }}
            </div>
            <div class="error-message"><b>errno：</b>{{ errMsg.errno }}</div>
            <div class="error-message"><b>sql：</b>"{{ errMsg.sql }}"</div>
            <div class="error-message"><b>code：</b>{{ errMsg.code }}</div>
            <div class="error-message">
              <b>sqlState：</b>{{ errMsg.sqlState }}
            </div>
          </template>
        </el-tab-pane>
        <el-tab-pane label="结果" name="result">
          <avue-crud
            v-if="tableData.length > 0"
            :option="option"
            :data="tableData"
            ref="crudSql"
          >
          </avue-crud>
          <div v-else>
            <span class="el-icon-info" style="color: rgb(144, 147, 153)"></span>
            暂无数据
          </div>
        </el-tab-pane>
        <el-tab-pane label="历史" name="history">
          <div v-if="recordList.length !== 0" class="recordWrap">
            <div
              v-for="item in recordList"
              :key="item"
              class="recordItem"
              @click="setCode(item)"
            >
              {{ item }}
            </div>
          </div>
          <div v-else>
            <span class="el-icon-info" style="color: rgb(144, 147, 153)"></span>
            暂无数据
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
// import CodemirrorEditor from '@/components/CodemirrorEditor'
import CodemirrorEditor from "@/views/DMDComponent/CodemirrorEditor.vue";
import * as api from "@/api/physicalData/physicalData";

export default {
  name: "SqlSearch",
  components: {
    CodemirrorEditor,
  },
  data() {
    return {
      code: "",
      source_table: "",
      label: "name",
      list: [],
      activeName: "info",
      selectData: [],
      tablesHeight: "245",
      runResult: "暂无数据", // 运行结果提示
      runType: 0, // 运行结果类型，0无结果、1成功、2警告、3异常
      tableData: [], // 运行结果的表数据展示
      columns: [], // 运行的表结构，对象元素，{label: '', value: ''}
      code: "", // 实时输入的代码
      runLoading: false, // 运行加载状态
      errMsg: {
        sqlMessage: "",
        errno: "",
        sql: "",
        code: "",
        sqlState: "",
      },
      option: {
        height: "calc(100vh - 420px)",
        calcHeight: "auto",
        tip: false,
        searchShow: false,
        index: true,
        align: "center",

        refreshBtn: false,
        columnBtn: false,
        menu: false,
        addBtn: false,
        column: [
          {
            label: "header1",
            prop: "header1",
          },
          {
            label: "header2",
            prop: "header2",
          },
        ],
      },
      recordList: [], // 查询历史记录
    };
  },
  mounted() {
    this.getRecord();
  },
  methods: {
    changeTab(tab, event) {
      if (Number(tab.index) === 2) {
        this.getRecord();
      }
    },
    getRecord() {
      const recordData = localStorage.getItem("recordList");
      if (recordData) {
        this.recordList = JSON.parse(recordData);
      }
    },
    setCode(code) {
      this.code = code;
      this.$refs.codemirrorEditor.changeCode(code);
    },
    copySQLOrder(item) {
      // 复制命令
      this.$refs.codemirrorEditor.setValue(item.sql);
    },
    onEditorInput(code) {
      // 编辑器输入事件
      this.code = code;
    },
    onSQLRun(code) {
      // SQL编辑器运行事件
      this.executeSql(code);
    },

    addRecord(code) {
      const recordData = localStorage.getItem("recordList");
      let newList = [];
      if (recordData) {
        const newArr = JSON.parse(recordData);
        newList = [...newArr];
      }

      if (newList.indexOf(code) > -1) {
        return;
      }
      newList.push(code);
      if (newList.length > 20) {
        newList = newList.slice(1);
      }
      localStorage.setItem("recordList", JSON.stringify(newList));
    },
    async executeSql(code) {
      // 执行SQL语句
      if (code.trim() === "") {
        this.$message.warning("请先编辑 SQL 命令！");
        return;
      }
      this.addRecord(code.trim());

      this.runLoading = true;
      this.tableData = [];
      this.columns = [];
      this.runResult = "执行中...";
      this.runType = 0;
      this.errMsg = {};
      try {
        const res = await api.executeDataByName({ sql: code });
        const { data,attr } = res.data.data;
        const { msg,success } = res.data;
        const startStr = code.split(" ")[0].toUpperCase(); // 避免大小写select的影响
        if (startStr.indexOf("SELECT") > -1) {
          if (success) {
            this.runType = 1;
            this.runResult = `成功查询 ${data.length} 条数据`;
            const column = attr.map(v=>({
              prop: v,
              label: v,
            }));
            this.option = {
                ...this.option,
                column,
              };
            if (data.length > 0) {
              this.tableData = [...data];
            }
             
          } else {
            this.runType = 3;
            this.runResult = "执行失败！";
            this.errMsg = {
              sqlMessage: msg,
              errno: "",
              sql: "",
              code,
              sqlState: "",
            };
          }
        } else {
          if (success) {
            this.runType = 1;
            this.runResult = `执行成功！`;
            this.runResult = `执行成功！ ${data} 条数据`;
          } else {
            this.runType = 3;
            this.runResult = "执行失败！";
            this.errMsg = {
              sqlMessage: msg,
              errno: "",
              sql: "",
              code,
              sqlState: "",
            };
          }
        }
        this.activeName = "info";
        this.runLoading = false;
      } catch (err) {
        this.activeName = "info";
        this.runLoading = false;
        this.runResult = "执行失败！" + err;
      }
    },
    open() {},
  },
};
</script>

<style lang="scss" scoped>
::v-deep .avue-crud__menu {
  display: none !important;
}
::v-deep .el-table th.el-table__cell > .cell {
  white-space: nowrap;
}

::v-deep  .el-tabs--border-card>.el-tabs__header .el-tabs__item{
  font-size: 12px;
}

// 右侧区域
.homeCode {
  width: 100%;
  height: 99%;

  // 工具栏
  .header-tools {
    height: 40px;

    .tools-list {
      list-style: none;
      padding: 0 0 0 20px;
      margin: 0;
      display: flex;
      align-items: center;
      height: 100%;
      font-size: 12px;
      color: #666;

      .tools-item {
        margin: 0px 10px;
        cursor: pointer;

        &:hover {
          color: #999;
        }

        .el-icon-video-play {
          color: #4bc451;
        }
        .el-icon-video-pause {
          color: #f35353;
        }
        .el-icon-document-checked,
        .el-icon-s-promotion,
        .el-icon-document {
          color: #4381e6;
        }
      }
    }
  }

  // 运行结果
  .tables-result {
    width: 100%;
    box-sizing: border-box;
    padding: 5px 0 0 1px;

    .el-tabs {
      .el-tab-pane {
        font-size: 12px;

        .error-message {
          margin: 8px 0px;
          box-sizing: border-box;
          padding-left: 14px;
        }
      }

      .el-table {
        // border: 1px solid red;
        height: 100px;
        overflow-y: scroll;
        font-size: 12px;
      }
      .el-table::-webkit-scrollbar {
        width: 5px;
      }
      .el-table::-webkit-scrollbar-thumb {
        border-radius: 10px;
        -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
        background: rgba(0, 0, 0, 0.2);
      }
    }
  }
}
.recordItem {
  cursor: pointer;
  padding: 5px;
}
.recordWrap {
  height: calc(100vh - 420px);
  overflow-y: scroll;
}
</style>
